package edu.vt.ece.rt.quorum.messsages.types;

import org.jgroups.Message;

import edu.vt.ece.rt.quorum.ClustersManager;
import edu.vt.ece.rt.quorum.messsages.QMessage;
import edu.vt.ece.rt.quorum.util.Names;
import edu.vt.ece.rt.util.Logger.Logger;

/*
 * Message to node to start benchmarks
 * @author Sudhanshu
 */

public class StartNow extends QMessage implements Runnable {
	boolean start;
	boolean reply;
	
	public StartNow(boolean b, boolean c) {
		super(MessageType.StartNow);
		start = b;
		reply = c;
	}

	@Override
	public void run() {
		if(!reply){	//Root is checking
			if(!start){
				Logger.debug("Waiting for Publishinging Completion");
				while(ClustersManager.done !=true);
				try {
					Logger.debug("Publishing done, replying root");
					ClustersManager.getCluster(Names.base).send(new Message(getSrcAddr(), new StartNow(false, true)));
				} catch (Exception e) {
					e.printStackTrace();
				}				
			}else{
				Logger.debug("Start from root");
				ClustersManager.startnow = true;
			}
		}else{
			if(ClustersManager.startSyncr.decrementAndGet() == 1){
				try {
					Logger.debug("Sending Start to all nodes");
					ClustersManager.getCluster(Names.base).send(new Message(null, new StartNow(true, false)));
					Thread.sleep(20);	//Approximate one side delay
					ClustersManager.startnow = true;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}	
}
